from django.core.paginator import PageNotAnInteger, Paginator
from django.http import JsonResponse
from django.shortcuts import render, HttpResponse
from django.views import View

from search.models import ArticleType, es


class IndexView(View):

    @staticmethod
    def get(request):
        return render(request, 'index.html')


class ResultView(View):

    @staticmethod
    def get(request):
        return render(request, 'result.html')

    @staticmethod
    def post(request):
        keyword = request.POST.get('keyword', None)
        res = es.search(index='jobbole',
                        body={
                            "query": {
                                "multi_match": {
                                    "query": keyword,
                                    "fields": ["tags", "title"]
                                }
                            },
                            "from": 0,
                            "size": 10,
                            "highlight": {
                                "fields": {
                                    "title": {},
                                    "tags": {},
                                    "content": {}
                                }
                            }
                        })
        total_nums = res['hits']['total']
        hit_list = []
        for hit in res['hits']['hits']:
            hit_dict = {}
            if 'title' in hit['highlight']:
                hit_dict['title'] = hit['highlight']['title'][0]
            else:
                hit_dict['title'] = hit['_source']['title']
            if 'content' in hit['highlight']:
                hit_dict['content'] = ';'.join(hit['highlight']['content'][:500])
            else:
                hit_dict['content'] = hit['_source']['content'][:500]
            hit_dict['url'] = hit['_source']['url']
            hit_dict['create_date'] = hit['_source']['create_date']
            hit_dict['score'] = hit['_score']
            hit_list.append(hit_dict)

        return render(request, 'result.html', {'total_num': total_nums, 'hit_list': hit_list, 'keyword': keyword})


class SuggestView(View):

    @staticmethod
    def get(request):
        return HttpResponse('suggest')

    @staticmethod
    def post(request):
        key_word = request.POST.get('key_word', None)
        re_data = []
        if key_word:
            s = ArticleType.search()
            s = s.suggest('my-suggest', key_word, completion={"field": "suggest",
                                                              "fuzzy": {"fuzziness": 1},
                                                              "size": 10})
            suggestions = s.execute()
            for match in suggestions.suggest['my-suggest'][0]['options']:
                re_data.append(match['_source']['title'])

        return JsonResponse({'re_data': re_data})
